from rest_framework import serializers
from areas.models import Area
from users.models import Address


class AreaSerializer(serializers.ModelSerializer):
    class Meta:
        model = Area
        fields = '__all__'


# 地址信息序列化
class AddressSerializers(serializers.ModelSerializer):
    # 序列化返回，string方法中指定的名字信息
    province = serializers.StringRelatedField(label='省', read_only=True)
    city = serializers.StringRelatedField(label='市', read_only=True)
    district = serializers.StringRelatedField(label='区', read_only=True)
    # 反序列化验证是省市区是以加——id传递过来的数据
    province_id = serializers.IntegerField(write_only=True)
    city_id = serializers.IntegerField(write_only=True)
    district_id = serializers.IntegerField(write_only=True)

    class Meta:
        model = Address
        # fields='__all__'
        exclude = ('user',)

    def create(self, validated_data):
        # 获取user对象
        user = self.context['request'].user
        validated_data['user'] = user

        user = super().create(validated_data)

        return user
